<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% String path=request.getContextPath(); String basePath=request.getScheme()+ "://" + request.getServerName() + ":" + request.getServerPort() + path+ "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<base href="<%=basePath%>">
<title>险别添加</title>
<%@ include file="/WEB-INF/jsp/common/common.jsp" %>
<style type="text/css">
.input_text{
width: 250px;
}
.select_1{
width: 250px;
}
</style>
<script src="js/jquery.validate.js" type="text/javascript" ></script>
<script src="js/jquery.divbox.js" type="text/javascript"></script>
<script src="js/json2.js" type="text/javascript"></script>


<script type="text/javascript">
var prodCode='${prodCode}';
var Formstatus=true;
<%-- 自定义Map对象 begin --%>
function Map() {   
    this.elements = new Array();   
    //获取MAP元素个数   
    this.size = function() {   
        return this.elements.length;   
    }   
     
    //判断MAP是否为空   
    this.isEmpty = function() {   
        return(this.elements.length < 1);   
    }   
     
    //删除MAP所有元素   
    this.clear = function() {   
        this.elements = new Array();   
    }   
     
    //向MAP中增加元素（key, value)    
    this.put = function(_key, _value) {   
        this.elements.push( {   
            key : _key,   
            value : _value   
        });   
    }   
     
    //删除指定KEY的元素，成功返回True，失败返回False   
    this.remove = function(_key) {   
        var bln = false;   
        try{   
            for(i = 0; i < this.elements.length; i++) {   
                if(this.elements[i].key == _key) {   
                    this.elements.splice(i, 1);   
                    return true;   
                }   
            }   
        } catch(e) {   
            bln = false;   
        }   
        return bln;   
    }   
     
    //获取指定KEY的元素值VALUE，失败返回NULL   
    this.get = function(_key) {   
        try{   
            for(i = 0; i < this.elements.length; i++) {   
                if(this.elements[i].key == _key) {   
                    return this.elements[i].value;   
                }   
            }   
        } catch(e) {   
            return null;   
        }   
    }   
     
    //获取指定索引的元素（使用element.key，element.value获取KEY和VALUE），失败返回NULL   
    this.element = function(_index) {   
        if(_index < 0 || _index >= this.elements.length) {   
            return null;   
        }   
        return this.elements[_index];   
    }   
     
    //判断MAP中是否含有指定KEY的元素   
    this.containsKey = function(_key) {   
        var bln = false;   
        try{   
            for(i = 0; i < this.elements.length; i++) {
            	//alert(this.elements[i].key+"---"+_key);
                if(this.elements[i].key == _key) {   
                	bln = true;   
                }   
            }   
        } catch(e) {   
        	bln = false;   
        }   
        return bln;   
    }   
     
    //判断MAP中是否含有指定VALUE的元素   
    this.containsValue = function(_value) {   
        var bln = false;   
        try{   
            for(i = 0; i < this.elements.length; i++) {   
                if(this.elements[i].value == _value) {   
                    bln = true;   
                }   
            }   
        } catch(e) {   
            bln = false;   
        }   
        return bln;   
    }   
     
    //获取MAP中所有VALUE的数组（ARRAY）   
    this.values = function() {   
        var arr = new Array();   
        for(i = 0; i < this.elements.length; i++) {   
            arr.push(this.elements[i].value);   
        }   
        return arr;   
    }   
     
    //获取MAP中所有KEY的数组（ARRAY）   
    this.keys = function() {   
        var arr = new Array();   
        for(i = 0; i < this.elements.length; i++) {   
            arr.push(this.elements[i].key);   
        }   
        return arr;   
    }   
}
<%-- 自定义Map对象 end --%>

$(document).ready(function() {
	<% if(request.getAttribute("dataException") != null){
		String dataException = (String)request.getAttribute("dataException");
	%>
		$.message("error","<%=dataException%>");
	<% } %>
	loadProdConInsureInfo({prodCode:prodCode});
});
<%--1.优先缓存DB中的数据，缓存key为序号 value为共保 对象 2.对缓存对象操作时从缓存容器cacheMap 中操作，点击保存才会入库DB3.缓存数据更新时先删除后添加--%>
var cacheDataMap = new Map();<%--缓存容器类似JavaMap--%>
var refreshTablePage;
var indexNo = "";
var handleType = "";
var preCompanyCode = "";
<%--缓存DB数据--%>
function cacheDBData(param){
	var DBarray = new Array();
	DBarray = param;
	if(null != DBarray && DBarray.length>0){
		for (var i=0;i<DBarray.length;i++){
			indexNo = DBarray[i].PRODCODE+'_'+DBarray[i].COMPANYCODE;//主键约束设置为KEY
			cacheDataMap.put(indexNo,DBarray[i]);
		}
	}
}
<%--刷新共保信息列表--%>
function refreshTable(refreshTablePage){
	var buttonStr = "<a href='javascript:void(0)' onClick='editConInsuReq(this);return false'>编辑</a>&nbsp;<a href='javascript:void(0)' onClick='delConInsuReq(this)'>删除</a>";
	var tableContent = creatTable("prodCode@TDH,companyCode@TDH,companyName,conRate,chiefFlag@TDH,chiefFlagDscp",refreshTablePage,buttonStr);
	var tableObj = $("#ProdConInsuTable");
	tableObj.find("tbody").remove();
	tableObj.append(tableContent);
}
<%--加载产品共保信息--%>
function loadProdConInsureInfo(param){
	$.openLoading();
	$.ajax({
		url : "nlifeProductConfig/loadProdConInsureInfo?"+new Date().getTime(),
		type : 'POST',
		async : true,
		dataType:'json',
		data:param,
		success : function(page) {
			$.closeLoading();
			if($.validate(page))return;
			refreshTable(page);
			cacheDBData(page.data);
			refreshTablePage = page;<%--记录DBpage--%>
		}
	});
}

function editConInsuReq(obj){
	handleType="update";
	var editTr = $(obj).parent('td').parent('tr')[0];
	preCompanyCode = editTr.childNodes[1].innerHTML;
	var conRate = editTr.childNodes[3].innerHTML;
	var chiefFlag = editTr.childNodes[4].innerHTML;
	$("#ecompanyCode").val(preCompanyCode);
	$("#econRate").val(conRate);
	$("#echiefFlag").val(chiefFlag);
	
	$("#editConInsuDiv").OpenDiv();
}
function vreset(){
	$("#ecompanyCode").val("");
	$("#econRate").val("");
	$("#echiefFlag").val(0);
	handleType="";
	preCompanyCode="";
}

function closeConInsuDiv(){
	$("#editConInsuDiv").CloseDiv();
	vreset();
}
<%--del--%>
function delcacheData(seqNo){
	if(cacheDataMap.containsKey(seqNo)){
		var bb = cacheDataMap.remove(seqNo);
	}
	refreshTablePage.data = cacheDataMap.values();
	refreshTable(refreshTablePage);
}
<%--temp cache--%>
function saveTemcacheConInsu(){
	var companyCode = $("#ecompanyCode").val();
	var companyName = $('#ecompanyCode').find("option:selected").text();
	var conRate = $("#econRate").val();
	var chiefFlag = $("#echiefFlag").val();
	var chiefFlagDscp = $("#echiefFlag").find("option:selected").text();

	if(0 == companyCode.length){
		$.message("error","请选择共保人");
		return;
	}
	if(0 == conRate.length){
		$.message("error","请输入共保比例");
		return;
	}else{
		var reg = new RegExp("^(([1-9][0-9]*)|0)(\.[0-9]{1,4})?$");
		var flag= reg.test(conRate);
	    if(!flag){
	    	$.message("error","输入的共保比例必须为有效数字且最多保留4位小数");
	    	return;
	    }
	    if(conRate>100){
	    	$.message("error","输入的共保比例必须小于100");
	    	return;
	    }
	}
	var temCurrSeqIndex = prodCode+'_'+companyCode;
	var temPreSeqIndex="";
	if("update"==handleType){
		temPreSeqIndex = prodCode+'_'+preCompanyCode;
	}
  	if("add"==handleType && cacheDataMap.containsKey(temCurrSeqIndex)){
		$.message("error","同一产品中同一共保人最多配置一条记录，请勿重复添加同一共保人");
    	return;
	}else if("update"==handleType && temCurrSeqIndex == temPreSeqIndex){
    	cacheDataMap.remove(temCurrSeqIndex);
    }else if("update"==handleType && temCurrSeqIndex != temPreSeqIndex){
		if(cacheDataMap.containsKey(temCurrSeqIndex)){
			$.message("error","同一产品中同一共保人最多配置一条记录，请勿重复添加同一共保人");
	    	return;
		}else if(cacheDataMap.containsKey(temPreSeqIndex)){
			cacheDataMap.remove(temPreSeqIndex);
		}
	}
	
	var data={"PRODCODE":prodCode,"COMPANYCODE":companyCode,"COMPANYNAME":companyName,"CONRATE":conRate,"CHIEFFLAG":chiefFlag,"CHIEFFLAGDSCP":chiefFlagDscp};
	cacheDataMap.put(temCurrSeqIndex,data);
	refreshTablePage.data = cacheDataMap.values();
	refreshTable(refreshTablePage);
	closeConInsuDiv();
}
function delConInsuReq(obj){
	var prodCode  = $(obj).parent('td').parent('tr')[0].childNodes[0].innerHTML;
	var companyCode  = $(obj).parent('td').parent('tr')[0].childNodes[1].innerHTML;
	$.dialog({
		type: "warn",
		content: "您确定要删除？",
		onOk: function() {
			delcacheData(prodCode+'_'+companyCode);
		}
	});
}
<%--open temp cache--%>
function addDataToCacheDiv(){
	handleType="add";
	$("#editConInsuDiv").OpenDiv();
}
<%--ergodic Map--%>
function saveProdConInsu(){
	if(2>cacheDataMap.size()){
		$.message("error","录入的共保信息记录数至少为2条");
		return;
	}
	var conConfNoArrUK = cacheDataMap.values();
	var  temConPropPercent=0;
	var  temMainConFlagCount = 0;
	for(var i = 0;i<conConfNoArrUK.length;i++){
		var temConConfNo = conConfNoArrUK[i];
		if(1==temConConfNo.CHIEFFLAG){
			temMainConFlagCount = temMainConFlagCount+1;
		}
		for(var j = i+1;j<conConfNoArrUK.length;j++){
			if(temConConfNo.COMPANYCODE == conConfNoArrUK[j].COMPANYCODE){
				$.message("error","同一产品中同一共保人最多配置一条记录，共保人名称:["+temConConfNo.COMPANYNAME+"]重复，请检查");
				return;
			}
		}
		temConPropPercent = temConPropPercent+parseFloat(temConConfNo.CONRATE);
	}
	if(1!=temMainConFlagCount){
		$.message("error","同一产品有且只能有一个首席标识为是的记录,请检查");
		return;
	}
	if(100!=temConPropPercent){
		$.message("error","同一产品所有记录共保比例之和必须等于100");
		return;
	}
	saveProdConInsuInfo(JSON.stringify(cacheDataMap.values()));
}
function saveProdConInsuInfo(param){
	if(!Formstatus){
		$.message("error","正在处理中");
		return;
	}
	Formstatus=false;
	$.openLoading();
	$.ajax({
		url : "nlifeProductConfig/saveProdConInsure?"+new Date().getTime(),
		type : 'POST',
		async : true,
		dataType:'json',
		data:{jsonDataStr:param,prodCode:prodCode},
		success : function(obj) {
			$.closeLoading();
			Formstatus=true;
			if($.validate(obj))return;
			cacheDataMap = new Map() <%--clear all cache Map container--%>
			loadProdConInsureInfo({prodCode:prodCode});
		}
	});
}

</script>
<style>
	.input_text {
	padding-left: 3px;
	}
</style>
</head>
<body>
<div class="right">
	      <div class="current">
	           <table class="current_table_1">
	              <tbody>
		              <tr>
		                <td><img src="./images/current_1.jpg"></td>
		                  <td class="current_table_1_td"><img src="images/current_1.png">&nbsp;您现在的位置：&nbsp;
			                  <span style=" color:#136bab; ">新意健险产品管理
			                  <span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span>产品配置
			                  <span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span>共保信息配置
			                  </span>
		                  </td>
		                  <td><img src="./images/current_3.jpg"></td>
		              </tr>
	           	  </tbody>
	           </table>
	      </div>
	      <div>
			<table class="table_05">
	              <tbody>
		    		  <tr>
 		              	<td style="line-height:23px;">
 		              		<font color="#3876bf"><b>产品代码：</b></font> ${prodCode}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color="#3876bf"><b>产品名称：</b></font>${prodName}
 		              	</td>
		              </tr>
	           	  </tbody>
	         </table> 
	      </div>
	      <div style="margin-top:10px;margin-right:35px;text-align: right;color:blue;font-size: 13px;">注:[添加]或[编辑]或[删除]共保信息记录只是暂存到页面，请点击[保存]完成最终修改</div>
 	      <!-- 已添加共保信息列表 -->
	      <div style="margin-top: 5px;">
	         <table class="table_02" id="ProdPlan" align="center" >
				<tbody>
					<tr>
						   <td colspan="6" style=" font-size:12px; font-weight:bold; text-align:left;color:#3876bf; line-height:27px;height:27px; background-image:url(images/centent_1.jpg)">&nbsp;已添加共保信息列表</td>
					</tr>
					<tr>
						<td>
							<table id="ProdConInsuTable" class="content_table_1">
								<thead>
									<tr class="f1">
					                   <th style="width:25%">共保人名称</th>
					                   <th style="width:25%">共保比例</th>
								       <th style="width:25%">首席标识</th>
								       <th style="width:25%">操作</th>
					              	</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</td>
					</tr>
				</tbody>
			</table>
			<div align="center">
			   <input class="input_button_3" name="" type="button" onclick="addDataToCacheDiv()" value="添加">&nbsp;&nbsp;
			   <input class="input_button_3" name="" type="button" onclick="saveProdConInsu()" value="保存">
			</div>
	      </div>     
</div>
	<!--   	添加模板 DIV 默认隐藏-->
	<div id="editConInsuDiv"  style="display:none;overflow-y:auto; width:60%">
			<div class="table_title_div">
					<table class="table_title" style='width:100%;height: 20px;'>
						<tr>
						<td width="10%"></td>
						<td width="80%" id="interfaceName"></td>
						<td width="10%" align="right"><img src="/manager/images/closedown.gif" alt="关闭"  onclick="closeConInsuDiv()"/></td>
						</tr>
					</table>
			</div>
			<!-- 修改id 名 -->
			<table class="table_02" id="addtempletTable" align="center">
				<tbody>
					<tr>
						<td>
							<table id="coverageTable"  class="content_table_1" style="height:120px;">
								<tbody>
									<tr>
					                  <td width="40%" style="text-align:right;border-right:0px;">共保方式：&nbsp;&nbsp;</td>
					                  <td width="60%" style="text-align:left">${conInsuCode}</td>
					                </tr>
					                <tr>
					                  <td width="40%" style="text-align:right;border-right:0px;">共保人名称：&nbsp;&nbsp;</td>
					                  <td width="60%" style="text-align:left"><select id="ecompanyCode" class="select_1" style="visibility: visible;width:250px;">
		                  					<option value="">---请选择---</option>
		                  					<c:forEach var ="insuCompanyLs" items="${insureCompanyTypeList}">
		                  						<option value="${insuCompanyLs.code}">${insuCompanyLs.codeName}</option>
		                  					</c:forEach>
		                  				  </select><span class="red">*</span></td>
					                </tr>
					                <tr>  
					                  <td width="40%" style="text-align:right;border-right:0px;">共保比例（%）(保留4位小数)：&nbsp;&nbsp;</td>
					                  <td width="60%" style="text-align:left"><input id="econRate" type="text" class="input_text"  maxlength="10" onKeyUp="clearNoNum(event,this)" onBlur="checkNum(this)"><span class="red">*</span></td>
					                </tr>
					                <tr>  
					                  <td width="40%" style="text-align:right;border-right:0px;">首席标识：&nbsp;&nbsp;</td>
					                  <td width="60%" style="text-align:left">
						                  <select id="echiefFlag" name = "ecField1" class="select_1" style="visibility: visible;">
			                  					<option value="0">否</option>
			                  					<option value="1">是</option>
			                  			  </select>
		                  			  </td>
					                </tr>
								</tbody>
							</table>
						</td>
					</tr>
				</tbody>
			</table>
			<div align="center">
			   <input class="input_button_3" name="" type="button" onclick="saveTemcacheConInsu()" value="暂存">&nbsp;&nbsp;
	           <input class="input_button_3" name="" type="button" onclick="closeConInsuDiv()" value="取消">
			</div>
	</div>
</body>
</html>